package com.stellar.oss.core.service;


import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.TosServerException;
import com.volcengine.tos.auth.StaticCredentials;
import com.volcengine.tos.model.object.PutObjectInput;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


public class TosStorageService implements StorageService {

    private final String bucketName;

    private final String endpoint;

    private final TOSV2 tosClient;


    public TosStorageService(String endpoint, String region, String accessKey, String secretKey, String bucketName) {
        StaticCredentials credentials = new StaticCredentials(accessKey, secretKey);
        this.tosClient = new TOSV2ClientBuilder().build(region, endpoint, credentials);
        this.bucketName = bucketName;
        this.endpoint = endpoint;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        // 参数校验
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("File cannot be null or empty");
        }

        // 生成随机文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + fileExtension;

        try (InputStream inputStream = file.getInputStream()) {
            // 构建上传请求
            PutObjectInput putInput = PutObjectInput.builder()
                    .bucket(bucketName)
                    .key(newFileName)
                    .content(inputStream)
                    .build();

            // 执行上传
            tosClient.putObject(putInput);

            // 生成访问URL（公有读场景）
            return String.format("https://%s.%s/%s", bucketName, endpoint, newFileName);

        } catch (TosClientException e) {
            // 操作失败，捕获客户端异常，一般情况是请求参数错误，此时请求并未发送
            System.out.println("putObject failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (TosServerException e) {
            // 操作失败，捕获服务端异常，可以获取到从服务端返回的详细错误信息
            System.out.println("putObject failed");
            System.out.println("StatusCode: " + e.getStatusCode());
            System.out.println("Code: " + e.getCode());
            System.out.println("Message: " + e.getMessage());
            System.out.println("RequestID: " + e.getRequestID());
        } catch (IOException e) {
            throw new RuntimeException("Failed to read file content", e);
        } catch (Exception e) {
            throw new RuntimeException("Failed to upload file to TOS", e);
        } catch (Throwable t) {
            // 作为兜底捕获其他异常，一般不会执行到这里
            System.out.println("putObject failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
        return null;
    }
}